import request from '@/utils/request'

export const fileApi = {
  // 获取文件列表
  getFileList(page = 1, pageSize = 10) {
    return request({
      url: '/blog-admin/storage/files',
      method: 'get',
      params: {
        page,
        pageSize
      }
    })
  },

  // 上传文件
  uploadFile(data) {
    return request({
      url: '/blog-admin/storage/files/upload',
      method: 'post',
      data,
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  // 下载文件
  downloadFile(filePath) {
    return request({
      url: `/blog-admin/storage${filePath}`,
      method: 'get',
      responseType: 'blob'
    }).then(response => {
      console.log(response);
      // 创建下载链接
      const url = window.URL.createObjectURL(new Blob([response.data]))
      const link = document.createElement('a')
      link.href = url
      // 从响应头获取文件名
      const contentDisposition = response.headers['content-disposition']
      let fileName = 'downloaded-file'
      if (contentDisposition) {
        fileName = decodeURIComponent(contentDisposition.split('filename=')[1])
      }
      link.setAttribute('download', fileName)
      document.body.appendChild(link)
      link.click()
      // 清理
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      return Promise.resolve()
    })
  },

  // 删除文件
  deleteFile(fileId) {
    return request({
      url: `/blog-admin/storage/files/${fileId}`,
      method: 'delete'
    })
  }
}